package com.peng.ivos.vehicle.service.impl;


import com.peng.ivos.application.mapper.ApplicationMapper;
import com.peng.ivos.application.pojo.dto.ApplicationQuery;
import com.peng.ivos.application.pojo.vo.ApplicationVO;
import com.peng.ivos.base.exception.ServiceException;
import com.peng.ivos.base.response.JsonResult;
import com.peng.ivos.base.response.PageData;
import com.peng.ivos.base.response.StatusCode;
import com.peng.ivos.vehicle.mapper.VehicleMapper;
import com.peng.ivos.vehicle.pojo.dto.VehicleQuery;
import com.peng.ivos.vehicle.pojo.dto.VehicleRepairSaveParam;
import com.peng.ivos.vehicle.pojo.dto.VehicleSaveParam;
import com.peng.ivos.vehicle.pojo.entity.Vehicle;
import com.peng.ivos.vehicle.pojo.entity.VehicleRepair;
import com.peng.ivos.vehicle.pojo.vo.VehicleRepairVO;
import com.peng.ivos.vehicle.pojo.vo.VehicleVO;
import com.peng.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 车辆管理业务层实现类
 * @author： Peng
 * @date： 2024/5/22
 * @version: 1.0
 */
@Service
@Slf4j
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    private VehicleMapper vehicleMapper;
    @Autowired
    private ApplicationMapper applicationMapper;

    @Override
    public JsonResult getVehicleList(VehicleQuery vehicleQuery) {
        if (vehicleQuery == null){
            log.error("车辆查询参数为空");
            return JsonResult.error(StatusCode.DATA_UNEXISTS, "车辆查询参数为空");
        }
        List<VehicleVO> vehicleList = vehicleMapper.selectByExample(vehicleQuery);
        return JsonResult.success("查询车辆列表成功",vehicleList);
    }

    @Override
    public JsonResult saveVehicle(VehicleSaveParam vehicleSaveParam) {
        if (vehicleSaveParam == null){
            log.error("车辆保存参数为空");
            return JsonResult.error(StatusCode.DATA_UNEXISTS,"车辆保存参数为空");
        }

        Vehicle vehicle = Vehicle.builder()
                .id(vehicleSaveParam.getId())
                .brand(vehicleSaveParam.getBrand())
                .license(vehicleSaveParam.getLicense())
                .model(vehicleSaveParam.getModel())
                .code(vehicleSaveParam.getCode())
                .displacement(vehicleSaveParam.getDisplacement())
                .status(vehicleSaveParam.getStatus())
                .type(vehicleSaveParam.getType())
                .color(vehicleSaveParam.getColor())
                .kilometers(vehicleSaveParam.getKilometers())
                .regTime(vehicleSaveParam.getRegTime())
                .buyTime(vehicleSaveParam.getBuyTime())
                .buyMoney(vehicleSaveParam.getBuyMoney())
                .batteryType(vehicleSaveParam.getBatteryType())
                .createTime(new Date())
                .updateTime(new Date())
                .geofenceBindStatus(vehicleSaveParam.getGeofenceBindStatus())
                .geofenceId(vehicleSaveParam.getGeofenceId())
                .build();
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setLicense(vehicleSaveParam.getLicense());
        vehicleQuery.setCode(vehicleSaveParam.getCode());
        if (vehicle.getId() != null){
            log.debug("更新车辆数据");
            vehicle.setUpdateTime(new Date());
            return vehicleMapper.updateVehicle(vehicle) > 0 ? JsonResult.success("车辆更新成功") : JsonResult.error("车辆更新失败");
        } else {
            log.debug("新增车辆数据");
            vehicle.setStatus("1");
            vehicle.setGeofenceBindStatus("0");
            if (vehicleMapper.selectByExample(vehicleQuery).size() > 0){
                throw new ServiceException(StatusCode.OPERATION_FAILED, "车牌号或车辆识别码已存在");
            }
            return vehicleMapper.addVehicle(vehicle) > 0 ? JsonResult.success("车辆添加成功") : JsonResult.error("车辆添加失败");
        }
    }

    @Override
    public JsonResult deleteVehicle(Long id) {
        if (id == null){
            log.error("车辆ID参数为空");
            return JsonResult.error(StatusCode.DATA_UNEXISTS,"车辆ID参数为空");
        }
        return vehicleMapper.delete(id) > 0 ? JsonResult.success("删除成功") : JsonResult.error("删除失败");
    }

    @Override
    public JsonResult updateVehicle(Long id, VehicleSaveParam vehicleSaveParam) {
        if (id == null || vehicleSaveParam == null){
            log.error("更新参数为空");
            return JsonResult.error(StatusCode.DATA_UNEXISTS,"更新参数为空");
        }else {
            Vehicle vehicle = Vehicle.builder()
                    .id(id)
                    .brand(vehicleSaveParam.getBrand())
                    .license(vehicleSaveParam.getLicense())
                    .model(vehicleSaveParam.getModel())
                    .code(vehicleSaveParam.getCode())
                    .displacement(vehicleSaveParam.getDisplacement())
                    .status(vehicleSaveParam.getStatus())
                    .type(vehicleSaveParam.getType())
                    .color(vehicleSaveParam.getColor())
                    .kilometers(vehicleSaveParam.getKilometers())
                    .regTime(vehicleSaveParam.getRegTime())
                    .buyTime(vehicleSaveParam.getBuyTime())
                    .buyMoney(vehicleSaveParam.getBuyMoney())
                    .batteryType(vehicleSaveParam.getBatteryType())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .geofenceBindStatus(vehicleSaveParam.getGeofenceBindStatus())
                    .geofenceId(vehicleSaveParam.getGeofenceId())
                    .build();
            return vehicleMapper.updateVehicle(vehicle) > 0 ? JsonResult.success("更新车辆信息成功") : JsonResult.error("更新车辆信息失败");
        }
    }

    @Override
    public JsonResult removeBindVehicle(Long vehicleId) {
        if (vehicleId == null) {
            return JsonResult.error(StatusCode.DATA_UNEXISTS,"车辆ID不能为空");
        }
        Vehicle vehicle = Vehicle.builder().id(vehicleId)
                .geofenceBindStatus("0")
                //之前的公用update方法动态拼接时条件是geofenceId!=null，
                // 此处要设置geofenceId为null，所以该动态拼接失效，要重新定制sql以完成业务需求
                .geofenceId(null)
                .updateTime(new Date())
                .build();
        return vehicleMapper.updateNullValue(vehicle) > 0 ? JsonResult.success("解绑车辆成功") : JsonResult.error("解绑车辆失败");
    }

    @Override
    public JsonResult addBindVehicle(Long bindId, Long vehicleId) {
        if (vehicleId == null || bindId == null) {
            return JsonResult.error(StatusCode.DATA_UNEXISTS,"参数不能为空");
        }
        Vehicle vehicle = Vehicle.builder()
                .id(vehicleId)
                .geofenceBindStatus("1")
                .geofenceId(bindId)
                .updateTime(new Date())
                .build();
        return vehicleMapper.updateVehicle(vehicle) > 0 ? JsonResult.success("绑定车辆成功") : JsonResult.error("绑定车辆失败");
    }

    @Override
    public JsonResult getVehicleListWithAvailable(Long id) {
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> geoVehicleVOList = vehicleMapper.selectByExample(vehicleQuery);
        VehicleQuery vehicleQuery1 = new VehicleQuery();
        vehicleQuery1.setGeofenceBindStatus("0");
        List<VehicleVO> availableVehicleVOList = vehicleMapper.selectByExample(vehicleQuery1);
        List<VehicleVO> resultVehicleList = Stream.concat(geoVehicleVOList.stream(), availableVehicleVOList.stream()).collect(Collectors.toList());
        return JsonResult.success(resultVehicleList);
    }

    @Override
    public JsonResult getRepairCarListByPage(VehicleQuery vehicleQuery) {

        List<VehicleRepairVO> repairCarList = vehicleMapper.getRepairCarList(vehicleQuery);
        PageData pageData = new PageData();
        pageData.setList(repairCarList);
        pageData.setTotal(vehicleMapper.getRepairCarListCount());
        log.debug("pagedata：{}", pageData);
        return JsonResult.success("维修车辆列表分页查询成功", pageData);
    }

    @Override
    public JsonResult getAllVehicleLicense() {
        List<VehicleVO> vehicleLicense = vehicleMapper.getAllVehicleLicense();
        return JsonResult.success("获取所有车辆车牌号成功", vehicleLicense);
    }

    @Override
    public JsonResult saveRepairVehicle(VehicleRepairSaveParam vehicleRepairSaveParam) {
        //根据车牌号获取车辆ID
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setLicense(vehicleRepairSaveParam.getLicense());
        List<VehicleVO> vehicleVOList = vehicleMapper.selectByExample(vehicleQuery);
        Long vehicleId = vehicleVOList.get(0).getId();
        //构建维修单数据
        VehicleRepair vehicleRepair = VehicleRepair.builder()
                .material(vehicleRepairSaveParam.getMaterial())
                .repairTime(vehicleRepairSaveParam.getRepairTime())
                .item(vehicleRepairSaveParam.getItem())
                .fee(vehicleRepairSaveParam.getFee())
                .addr(vehicleRepairSaveParam.getAddr())
                .vehicleId(vehicleId)
                .userId(vehicleRepairSaveParam.getUserId())
                .username(vehicleRepairSaveParam.getUsername())
                .repairStatus(vehicleRepairSaveParam.getRepairStatus())
                .build();
        if (vehicleRepairSaveParam.getRepairId() == null){
            log.debug("新建车辆维修单");
            //更新车辆状态为 3-维修中
            Vehicle vehicle = Vehicle.builder()
                    .license(vehicleRepairSaveParam.getLicense())
                    .id(vehicleId)
                    .build();
            if ("1".equals(vehicleRepairSaveParam.getRepairStatus())){
                vehicle.setStatus("3");
                vehicle.setUpdateTime(new Date());
            }
            Integer i1 = vehicleMapper.updateVehicle(vehicle);
            //保存车辆维修单数据
            Integer i2 = vehicleMapper.saveRepairVehicle(vehicleRepair);
            //校验是否保存成功
            if (i1 > 0 && i2 > 0){
                return JsonResult.success("新建车辆维修单成功");
            } else {
                return JsonResult.error("新建车辆维修单失败");
            }
        } else {
            //todo 更新车辆维修单
            log.debug("更新车辆维修单");
            vehicleRepair.setId(Long.toString(vehicleRepairSaveParam.getRepairId()));
            VehicleRepairVO vehicleRepairVO = vehicleMapper.getRepairCarByRepairId(vehicleRepairSaveParam.getRepairId());
            String repairStatus = vehicleRepairVO.getRepairStatus();
            Vehicle vehicle = new Vehicle();
            vehicle.setId(vehicleId);
            //若维修单状态修改则更新车辆更新时间
            if (!repairStatus.equals(vehicleRepair.getRepairStatus())) {
                vehicle.setUpdateTime(new Date());
            }
            //更新维修单状态
            Integer i1 = vehicleMapper.updateVehicleRepair(vehicleRepair);

            //更新车辆状态，维修单状态修改为1-维修中时，车辆状态修改为3-维修
            if ("1".equals(vehicleRepair.getRepairStatus())){
                vehicle.setStatus("3");
            } else if ("0".equals(vehicleRepair.getRepairStatus())) {
                //更新车辆状态，维修单状态修改为0-已完成时，判断通过申请表判断车辆是否被占用，占用则更新车辆状态为2-占用，否则更新为1-空闲
                ApplicationQuery query = new ApplicationQuery();
                query.setVehicleId(vehicleId);
                query.setStatus("60");
                List<ApplicationVO> applicationVOList = applicationMapper.selectApplicationByExample(query);
                if (applicationVOList.size() > 0){
                    vehicle.setStatus("2");
                } else {
                    vehicle.setStatus("1");
                }
            }
            vehicleMapper.updateVehicle(vehicle);

            if (i1 > 0){
                return JsonResult.success("更新车辆维修单成功");
            } else {
                return JsonResult.error("更新车辆维修单失败");
            }
        }
    }

    @Override
    public JsonResult getRepairCarByRepairId(String repairId) {
        Long id = Long.parseLong(repairId);
        VehicleRepairVO vehicleRepairVO = vehicleMapper.getRepairCarByRepairId(id);
        return JsonResult.success("获取车辆维修单详情成功", vehicleRepairVO);
    }

    @Override
    public JsonResult deleteRepairVehicle(Long repairId) {
        VehicleRepairVO vehicleRepairVO = vehicleMapper.getRepairCarByRepairId(repairId);
        Long vehicleId = vehicleRepairVO.getVehicleId();
        log.debug("删除车辆维修单信息：{}",vehicleRepairVO);
        //更新车辆状态为原始状态
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        ApplicationQuery query = new ApplicationQuery();
        query.setVehicleId(vehicleId);
        query.setStatus("60");
        List<ApplicationVO> applicationVOList = applicationMapper.selectApplicationByExample(query);
        if (applicationVOList.size() > 0){
            vehicle.setStatus("2");
        } else {
            vehicle.setStatus("1");
        }
        Integer i1 = vehicleMapper.updateVehicle(vehicle);

        //删除维修单记录
        Integer i2 = vehicleMapper.deleteRepairVehicle(repairId);
        if (i1 > 0 && i2 > 0){
            return JsonResult.success("删除车辆维修单成功");
        } else {
            return JsonResult.error("删除车辆维修单失败");
        }
    }
}
